package com.ruoyi.system.filter;

import com.ruoyi.domain.utils.GatewayUtils;
import com.ruoyi.domain.utils.JwtUtils;
import com.ruoyi.domain.utils.StringUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;

/**
 * @author 姚炜琦
 * @Classname AuthFilter
 * @Description TODO
 * @Date 2022/8/9 9:46
 */
@Configuration
@Log4j2
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private final ArrayList<String> pathList = new ArrayList<String>(){{
        add("/loginClient/login.html");
        add("/system/user/getCode/**");
        add("/system/user/upload/**");
        add("/system/user/upPic/**");
    }};

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String path = request.getURI().getPath();
        Long startTime = System.currentTimeMillis();
        log.info("开始网关过滤！");
        if (StringUtils.matches(path,pathList)){
            log.info("网关过滤耗时：【{}】MS",System.currentTimeMillis() - startTime);
            return chain.filter(exchange);
        }
        String token = headers.getFirst(JwtUtils.TOKEN);
        if (StringUtils.isEmpty(token)){
            log.info("网关过滤耗时：【{}】MS",System.currentTimeMillis() - startTime);
            return GatewayUtils.errorResponse(exchange,"请携带令牌");
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null){
            log.info("网关过滤耗时：【{}】MS",System.currentTimeMillis() - startTime);
            return GatewayUtils.errorResponse(exchange,"token违法");
        }
        String userKey = JwtUtils.getUserKey(claims);
        Boolean hasKey = redisTemplate.hasKey(JwtUtils.LOGIN_TOKEN_KEY + userKey);
        if (!hasKey){
            log.info("网关过滤耗时：【{}】MS",System.currentTimeMillis() - startTime);
            return GatewayUtils.errorResponse(exchange,"token已过期");
        }
        log.info("网关过滤耗时：【{}】MS",System.currentTimeMillis() - startTime);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
